/**
 * Created on 2007-05-23 13:01
 */
package game.score;

import internet.InternetReader;

import java.util.ArrayList;
import java.util.Iterator;

import tools.xmlTools.*;

/**
 * @author David Wallin
 */
public class HighscoreList
{
	/**
	 * The highscores
	 */
	private ArrayList<Highscore>		m_Highscores;
	private static final String			HIGHSCORE_NODE_NAME = "highscore";
	
	/**
	 * Default constructor
	 */
	public HighscoreList()
	{
		m_Highscores = new ArrayList<Highscore>();
	}
	
	/**
	 * Reads the highscores from the internetz
	 */
	public void readHighscores()
	{
		XMLTool					reader = new XMLTool();
		XMLReadOnlyDocument		document = null;
		XMLReadOnlyNode			parentNode = null;
		XMLReadOnlyNode			highscoreNode = null;
		int						highscores = 0;
		boolean					readOK = false;
		
		m_Highscores.clear();
		
		try
		{
			document = reader.getDocument(InternetReader.getTop10Location());
			readOK = true;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		if(readOK)
		{
			parentNode = document.getNode();
			highscores = parentNode.getOccurrences(HIGHSCORE_NODE_NAME);
			
			for(int i = 0; i < highscores; i++)
			{
				highscoreNode = parentNode.getNode(HIGHSCORE_NODE_NAME, i);
				String name = highscoreNode.getValue("name", 0);
				int score = Integer.parseInt(highscoreNode.getValue("score", 0));
				int level = Integer.parseInt(highscoreNode.getValue("level", 0));
				String date = highscoreNode.getValue("time", 0);
				//TODO fix Timestamp
				m_Highscores.add(new Highscore(name, score, level, date));
			}
		}
	}
	
	/**
	 * Gets the highest score in the highscore list, provided the xml delivering the highscores
	 * is formatted to put the highest score at the top of the document
	 * 
	 * @return the highest score in the list
	 */
	public int getTopScore()
	{
		int topScore = -1;
		
		if(m_Highscores.size() > 0)
		{
			topScore = m_Highscores.get(0).getScore();
		}
		
		return topScore;
	}
	
	public String toString()
	{
		return stringRepresentation();
	}
	
	private String stringRepresentation()
	{
		String					rep = "";
		Iterator<Highscore>		it = m_Highscores.iterator();
		
		while(it.hasNext())
		{
			rep += it.next().toString();
		}
		
		if(rep.equals(""))
		{
			rep = "no highscores could be read";
		}
		
		return rep;
	}
}
